package com.fengshang.wedding.web.view;

import static com.fengshang.wedding.domain.Constants.GENDER_FEMALE;
import static com.fengshang.wedding.domain.Constants.GENDER_MALE;
import static com.fengshang.wedding.domain.Constants.ROLE_ADMIN;
import static com.fengshang.wedding.domain.Constants.ROLE_GUEST;
import static com.fengshang.wedding.domain.Constants.ROLE_USER;
import static com.fengshang.wedding.web.controller.Response.RESULT_CODE;
import static com.fengshang.wedding.web.controller.Response.RESULT_MESSAGE;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.web.servlet.View;

import com.fengshang.wedding.domain.model.api.IUser;
import com.fengshang.wedding.domain.model.api.User;
import com.fengshang.wedding.utils.I18NHelper;
import com.fengshang.wedding.web.controller.Response;
/**
 * 
 *@author gembin@gmail.com
 * 
 */
public class JsonView implements View {
   
	private static final Logger logger = Logger.getLogger(JsonView.class);
	public static final String DATA= "data";
	public static final String MODEL= "data.model";
	public static final String RESPONSE= "data.response";
	
	
	//public static final String SINGLE_OBJECT= "single.object";
	//public static final String DATA_COLLECTION= "data.collection";
	public static final String ID= "id";
	public static final String ROWS= "rows";
	public static final String CELL= "cell";
	public static final String TOTAL= "total";
	public static final String PAGE= "page";
	public static final String CONTENT_TYPE = "application/json; charset=UTF-8";
	public static final int TYPE_SINGLE_OBJECT=1;
	public static final int TYPE_COLLECTION_OBJECT=2;
	
	private int dataType = TYPE_COLLECTION_OBJECT; //default value
	private I18NHelper i18NHelper;
	 
	public void setI18NHelper(I18NHelper i18nHelper) {
		i18NHelper = i18nHelper;
	}

	public void setDataType(int dataType) {
		this.dataType = dataType;
	}

	public String getContentType() {
		return CONTENT_TYPE;
	}

	@SuppressWarnings("unchecked")
	public void render(Map model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		/*String page=request.getParameter("page");
		String pageSize = request.getParameter("rp");   
		String query = request.getParameter("query");   
		String sortname = request.getParameter("sortname");  
		System.out.println("pageXXXX-->"+page);
		System.out.println("pageSizeXXXX-->"+pageSize);
		System.out.println("queryXXXX-->"+query);
		System.out.println("sortnameXXXX-->"+sortname); */
		JSONObject jsonObject =null;
		Object dataModel = model.get(MODEL);
		Object dataResponse = model.get(RESPONSE);
		if(!(dataResponse instanceof Response))
			throw new RuntimeException("Invalid Response Object:"+dataResponse);
		Response res=(Response)dataResponse;
		//data response to the client
		Map data =new HashMap();
		data.put(RESULT_CODE, res.getResultCode()); 
		data.put(RESULT_MESSAGE,res.getResultMessage());
		if(dataModel==null){
			jsonObject = new JSONObject(data);   
		}
		switch(dataType){
		case TYPE_SINGLE_OBJECT:
			if(dataModel!=null && dataModel instanceof IUser){
				Map userData=new HashMap();
				IUser user=(IUser)dataModel;
				userData.put("id",user.getId());
				userData.put("name",user.getName());
				userData.put("email",user.getEmail());
				userData.put("mobile",user.getMobile());
				userData.put("gender",user.getGender());
				userData.put("phone",user.getPhone());
				userData.put("qq",user.getQq());
				userData.put("website",user.getWebsite());
				data.put(DATA,userData);
				jsonObject = new JSONObject(data);   
			}
			break;
		case TYPE_COLLECTION_OBJECT:
			Object totalPage = model.get(TOTAL);
			Object currentPage = model.get(PAGE);
			logger.debug("currentPage="+currentPage);
			if(dataModel!=null && dataModel instanceof Collection){
				Iterator it= ((Collection)dataModel).iterator();
				List mapList = new ArrayList();  
				while(it.hasNext()){
					User user=(User) it.next();
					Map cellMap = new HashMap();   
					cellMap.put(ID, user.getId());  
					String gender="",role="";
					switch(user.getGender()){
					case MALE:  gender=i18NHelper.getValue(GENDER_MALE);break;
					case FEMALE:  gender=i18NHelper.getValue(GENDER_FEMALE);break;
					}
					switch(user.getRole()){
					case GUEST:  role=i18NHelper.getValue(ROLE_GUEST);break;
					case USER:  role=i18NHelper.getValue(ROLE_USER);break;
					case ADMIN:  role=i18NHelper.getValue(ROLE_ADMIN);break;
					}
					cellMap.put(CELL, new Object[]{user.getId(), user.getName(),user.getPassword(), user.getEmail(),
							user.getQq(),user.getMobile(),user.getPhone(),gender,user.getWebsite(),role});      
					mapList.add(cellMap);   
				}
				data.put(ROWS, mapList);   
				data.put(TOTAL, totalPage);   
				data.put(PAGE, currentPage); 
				jsonObject = new JSONObject(data);   
			}
			break;
		default: 
			 
		}
		
		logger.debug("json: " + jsonObject.toString());
		response.setCharacterEncoding("utf-8");   
		response.setHeader("Pragma", "no-cache");   
        response.setHeader("Cache-Control", "no-cache, must-revalidate");   
        response.setHeader("Pragma", "no-cache");  
		response.getWriter().write(jsonObject.toString());
	}

}
